package com.mflex.mwms.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import androidx.annotation.Nullable;

import com.mflex.mwms.R;
import com.mflex.mwms.adapter.ShipmentOffAdapter;
import com.mflex.mwms.model.CustomApiResult;
import com.mflex.mwms.model.Task;
import com.mflex.mwms.utils.MMKVUtils;
import com.mflex.mwms.utils.MessageUtils;
import com.mflex.mwms.utils.XToastUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.CallBackProxy;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JsonUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ShipmentOffActivity extends BaseActivity implements AdapterView.OnItemClickListener {
    @BindView(R.id.stv_Warehouse)
    EditText stvWarehouse;

    @BindView(R.id.stv_JLNO)
    EditText stvJLNO;

    @BindView(R.id.button_clear)
    Button buttonClear;

    @BindView(R.id.button_query)
    Button buttonQuery;

    @BindView(R.id.lvTaskList)
    ListView lvTaskList;

    MiniLoadingDialog mMiniLoadingDialog;

    List<Task> taskList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shipment_off);
        ButterKnife.bind(this);
        mMiniLoadingDialog = WidgetUtils.getMiniLoadingDialog(this, "加载...");

        taskList = new ArrayList<>();
        ShipmentOffAdapter shipmentOffAdapter = new ShipmentOffAdapter(this, taskList);
        lvTaskList.setAdapter(shipmentOffAdapter);

        stvWarehouse.setFocusable(false);
        stvWarehouse.setText(MMKVUtils.getString("Warehose", ""));

        stvJLNO.setOnKeyListener(this);
        buttonClear.setOnClickListener(this);
        buttonQuery.setOnClickListener(this);
        lvTaskList.setOnItemClickListener(this);
        requestTask(this.getCurrentFocus());
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_clear:
                clearButtonMd(view);
                break;
            case R.id.button_query:
                queryButtonMd(view);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && (i == 66 || i == 61)) {
            switch (view.getId()) {
                case R.id.stv_Warehouse:
//                    checkWarehouse(view);
                    break;
                case R.id.stv_BoxNumber:
                    requestTask(view);
                    break;
                default:
                    break;
            }
        }
        return false;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

//        if (StringUtils.equals("1", taskList.get(i).getPickingTaskStatus())) {
//            Intent intent = new Intent(ShipmentOffActivity.this, ShipmentOffDetailActivity.class);
//            intent.putExtra("task", JsonUtil.toJson(taskList.get(i)));
//            startActivityForResult(intent, 0);
//        } else {
        mMiniLoadingDialog.show();
        XHttp.get("api/ShelfOff/UpdateShipmentShelfOff")
                .params("TaskId", taskList.get(i).getTaskId())
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(120000)
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {
                    @Override
                    public void onSuccess(String response) {
                        mMiniLoadingDialog.dismiss();
                        Intent intent = new Intent(ShipmentOffActivity.this, ShipmentOffDetailActivity.class);
                        intent.putExtra("task", JsonUtil.toJson(taskList.get(i)));
                        startActivityForResult(intent, 0);
                    }

                    @Override
                    public void onError(ApiException e) {
                        mMiniLoadingDialog.dismiss();
//                        if (e.getCode() == 100) {
//                            new MaterialDialog.Builder(ShipmentOffActivity.this)
//                                    .iconRes(R.drawable.icon_warning)
//                                    .title(R.string.tip_warning)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
//                        if (e.getCode() == 200) {
//                            new MaterialDialog.Builder(ShipmentOffActivity.this)
//                                    .iconRes(R.drawable.icon_tip)
//                                    .title(R.string.tip_infos)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
                        MessageUtils.errorMsgAndVoice(ShipmentOffActivity.this, e);
                    }
                }) {
                });
//        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        requestTask(ShipmentOffActivity.this.getCurrentFocus());
    }

    private void requestTask(View v) {
        mMiniLoadingDialog.show();
        XHttp.get("api/Task/GetShipmentTaskList")
                .params("JLNo", stvJLNO.getText().toString())
                .params("TaskStatusName", "1")
                .params("PickingDetailStatus", "0")
                .params("CurrentWarehouse", MMKVUtils.getString("Warehose", ""))
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(120000)
                .execute(new CallBackProxy<CustomApiResult<List<Task>>, List<Task>>(new SimpleCallBack<List<Task>>() {

                    @Override
                    public void onSuccess(List<Task> response) {
                        mMiniLoadingDialog.dismiss();
                        taskList = response;
                        Collections.sort(taskList, new Comparator<Task>() {
                            @Override
                            public int compare(Task t0, Task t1) {
                                if (StringUtils.isEmpty(t0.getStockoutDetails().get(0).getPriority()) && StringUtils.isEmpty(t1.getStockoutDetails().get(0).getPriority())) {
                                    return -1;
                                } else if (!StringUtils.isEmpty(t0.getStockoutDetails().get(0).getPriority()) && StringUtils.isEmpty(t1.getStockoutDetails().get(0).getPriority())) {
                                    return -1;
                                } else if (StringUtils.isEmpty(t0.getStockoutDetails().get(0).getPriority()) && !StringUtils.isEmpty(t1.getStockoutDetails().get(0).getPriority())) {
                                    return 1;
                                } else if (!StringUtils.isEmpty(t0.getStockoutDetails().get(0).getPriority()) && !StringUtils.isEmpty(t1.getStockoutDetails().get(0).getPriority())) {
                                    if (t0.getStockoutDetails().get(0).getPriority().compareTo(t1.getStockoutDetails().get(0).getPriority()) > 0) {
                                        return 1;
                                    } else if (t0.getStockoutDetails().get(0).getPriority().compareTo(t1.getStockoutDetails().get(0).getPriority()) == 0) {
                                        return 0;
                                    } else {
                                        return -1;
                                    }
                                } else {
                                    return 0;
                                }
                            }
                        });
                        ShipmentOffAdapter shipmentOffAdapter = new ShipmentOffAdapter(ShipmentOffActivity.this, taskList);
                        lvTaskList.setAdapter(shipmentOffAdapter);
                    }

                    @Override
                    public void onError(ApiException e) {
                        mMiniLoadingDialog.dismiss();
                        stvJLNO.setText("");
                        stvJLNO.requestFocus();
//                        if (e.getCode() == 100) {
//                            new MaterialDialog.Builder(v.getContext())
//                                    .iconRes(R.drawable.icon_warning)
//                                    .title(R.string.tip_warning)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
//                        if (e.getCode() == 200) {
//                            new MaterialDialog.Builder(v.getContext())
//                                    .iconRes(R.drawable.icon_tip)
//                                    .title(R.string.tip_infos)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
                        MessageUtils.errorMsgAndVoice(ShipmentOffActivity.this, e);
                    }
                }) {
                });
    }

    private void clearButtonMd(View v) {
        stvJLNO.setText("");

        taskList = new ArrayList<>();
        ShipmentOffAdapter shipmentOffAdapter = new ShipmentOffAdapter(ShipmentOffActivity.this, taskList);
        lvTaskList.setAdapter(shipmentOffAdapter);
        XToastUtils.success("重置成功！");
    }

    private void queryButtonMd(View v) {
        requestTask(v);
    }
}